package org.holynite.fieldmanage.repositories.impl

import org.holynite.fieldmanage.entities.Administrator
import org.holynite.fieldmanage.persistence.AdministratorEAO
import org.holynite.fieldmanage.repositories.BaseEAO

import javax.ejb.Stateless

/**
 * Created by midnite on 15/1/7.
 */
@Stateless(name = "adminEAO")
class AdministratorEAOImpl extends BaseEAO implements AdministratorEAO {
	@Override
	int checkAdministratorAmount() {
		def query = em.createQuery("select count(*) from Administrator")
		Object[] result = query.singleResult
		result[0] as int
	}

	@Override
	int checkAvaliableAdministrator() {
		def query = em.createQuery("select count(*) from Administrator as a where a.disabled = false")
		Object[] result = query.singleResult
		result[0] as int
	}

	@Override
	Boolean checkWorkIdUsable(String workId) {
		def query = em.createQuery("select count(*) from Administrator where workdId = :workId")
		query.setParameter("workId", workId)
		Object[] result = query.singleResult
		result[0] == 0
	}

	@Override
	Administrator findAdministratorByName(String name) {
		def query = em.createQuery("select a from Administrator as a where a.name = :name")
		query.setParameter("name", name)
		query.singleResult as Administrator
	}

	@Override
	List<Administrator> searchAdministrators(String keyword) {
		def result
		if (keyword.length() > 0) {
			def query = em.createQuery("select a from Administrator as a where a.workdId like :keyword or a.name like :keyword order by a.create asc")
			query.setParameter("keyword", "%$keyword%".toString())
			result = query.resultList
		} else {
			def query = em.createQuery("select a from Administrator as a order by a.create asc")
			result = query.resultList
		}
		result as List<Administrator>
	}
}
